﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class RoleListPage : Page, INavigableView<RoleListViewModel>
    {
        public RoleListViewModel ViewModel { get; }

        public RoleListPage(RoleListViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTreeCommand.ExecuteAsync(null);
        }

        [RelayCommand]
        private async Task Add()
        {
            await Edit(null);
        }

        [RelayCommand]
        private async Task EditById(string id)
        {
            if (!id.IsNullOrEmpty())
            {
                RoleEditPage page = App.GetService<RoleEditPage>();
                RoleEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IRoleService>.Instance.GetAsync(id.ToInt32());
                await page.ViewModel.InitData(id.ToInt32());
                page.ViewModel.IsEdit = true;
                page.Height = 720.0;
                page.Width = 1000.0;
                page.ShowDialog();
           
                if (page.ViewModel.Result?.Success == true)
                {
                    await ViewModel.GetData();
                }
            }
        }

        [RelayCommand]
        private async Task Edit(RoleInfo info)
        {
            RoleEditPage page = App.GetService<RoleEditPage>();
            if (info != null)
            {
                RoleEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IRoleService>.Instance.GetAsync(info.Id);
                await page.ViewModel.InitData(info.Id);
                page.ViewModel.IsEdit = true;
                page.Height = 720.0;
                page.Width = 1000.0;
            }
            else
            {
                page.ViewModel.Item = new RoleInfo();
                page.ViewModel.UserInfos.Clear();
                page.ViewModel.OuInfos.Clear();
                page.ViewModel.IsEdit = false;
                page.Height = 530.0;
                page.Width = 800.0;
                string company_ID = (ViewModel.PageDto.Company_ID.IsNullOrEmpty() ? App.ViewModel.UserInfo.Company_ID : ViewModel.PageDto.Company_ID);
                page.ViewModel.Item.Company_ID = company_ID;
            }
            page.ShowDialog();
            
            if (page.ViewModel.Result?.Success == true)
            {
                await ViewModel.GetData();
            }
        }

        [RelayCommand]
        private async Task Delete(RoleInfo info)
        {
            await ViewModel.DeleteCommand.ExecuteAsync(info);
            await ViewModel.GetData();
        }

        [RelayCommand]
        private void Search()
        {
            ViewModel.PageDto.Company_ID = null;
            ViewModel.SearchCommand.ExecuteAsync(null);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
            {
                return;
            }
            if (selectedItems != null)
            {
                List<RoleInfo> list = new List<RoleInfo>();
                foreach (RoleInfo item in selectedItems)
                {
                    list.Add(item);
                }
                ViewModel.SelectedItems = list;
            }
            else
            {
                ViewModel.SelectedItems = null;
            }
        }

        [RelayCommand]
        private void ImportExcel()
        {
            var importPage = App.GetService<ImportExcelPage>();
            importPage.ViewModel.Items?.Clear();
            importPage.ViewModel.TemplateFile = "角色信息-模板.xls";
            importPage.OnDataSave -= ExcelData_OnDataSave;
            importPage.OnDataSave += ExcelData_OnDataSave;
            ViewModel.Navigate(typeof(ImportExcelPage));
        }

        private string GetRowData(DataRow row, string columnName)
        {
            string result = "";
            if (row.Table.Columns.Contains(columnName))
            {
                result = row[columnName].ToString();
            }
            return result;
        }

        private async Task<bool> ExcelData_OnDataSave(DataRow dr)
        {
            DateTime dateTime = Convert.ToDateTime("1900-01-01");
            RoleInfo roleInfo = new RoleInfo();
            roleInfo.PID = GetRowData(dr, "父ID").ToInt32();
            roleInfo.HandNo = GetRowData(dr, "角色编码");
            roleInfo.Name = GetRowData(dr, "角色名称");
            roleInfo.Note = GetRowData(dr, "备注");
            roleInfo.SortCode = GetRowData(dr, "排序码");
            roleInfo.Category = GetRowData(dr, "角色分类");
            roleInfo.Company_ID = GetRowData(dr, "所属公司ID");
            roleInfo.CompanyName = GetRowData(dr, "所属公司名称");
            roleInfo.Creator = GetRowData(dr, "创建人");
            roleInfo.Creator_ID = GetRowData(dr, "创建人ID");
            string rowData = GetRowData(dr, "创建时间");
            if (!string.IsNullOrEmpty(rowData))
            {
                if (DateTime.TryParse(rowData, out var result) && result > dateTime)
                {
                    roleInfo.CreateTime = result;
                }
            }
            else
            {
                roleInfo.CreateTime = DateTime.Now;
            }
            return await BLLFactory<IRoleService>.Instance.InsertAsync(roleInfo);
        }

        private async void roleTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is RoleAndDeptTreeNode roleAndDeptTreeNode)
            {
                ViewModel.RoleTreeModel.SelectNode = roleAndDeptTreeNode;
                ViewModel.PageDto.Company_ID = roleAndDeptTreeNode.CompanyId;
                await ViewModel.GetData();
            }
        }

        private void SearchBarRole_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.RoleTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.RoleTreeModel.FilteredTreeItems = ViewModel.RoleTreeModel.TreeItems;
                return;
            }
            ViewModel.RoleTreeModel.FilteredTreeItems = ViewModel.RoleTreeModel.TreeItems.FindRoleNodes((RoleAndDeptTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }

        private async void roleTree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (roleTree.SelectedItem is RoleAndDeptTreeNode roleAndDeptTreeNode && !roleAndDeptTreeNode.RoleId.IsNullOrEmpty())
            {
                await Edit(await BLLFactory<IRoleService>.Instance.GetAsync(roleAndDeptTreeNode.RoleId.ToInt32()));
            }
        }
    }
}
